package com.iemp.web.controller.base.impl;

import com.iemp.bean.IEntity;
import com.iemp.exception.entity.universal.CustomNotFoundException;
import com.iemp.service.base.AbstractService;
import com.iemp.web.controller.base.IBaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.lang.reflect.ParameterizedType;

@CrossOrigin
public abstract class BaseController<E extends IEntity, S extends AbstractService<E>> implements IBaseController<E> {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    protected final S genericService;
    private Class<E> clazz = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

    public BaseController(S genericService) {
        this.genericService = genericService;
    }

    @Override
    public E selectById(Integer id) {
        E byId = genericService.selectById(id);
        if (byId == null) {
            CustomNotFoundException e =
                    new CustomNotFoundException(clazz, id);
            log.error("exception occured:{}", e.toString());
            throw e;
        }
        return byId;
    }

    @Override
    public Integer deleteById(Integer id) {
        E byId = genericService.selectById(id);
        if (byId == null) {
            CustomNotFoundException e =
                    new CustomNotFoundException(clazz, id);
            log.error("exception occured:{}", e.toString());
            throw e;
        }
        return genericService.deleteById(id);
    }

    @Override
    public Integer insertSelective(E entity) {
        return genericService.insertSelective(entity);
    }

    @Override
    public Integer updateByIdSelective(E entity) {
        return genericService.updateByIdSelective(entity);
    }

}
